# from pytypes import typechecked
from datetime import datetime, timedelta
from functools import lru_cache
import numpy as np
import pandas as pd
from sqlalchemy import create_engine, Engine
import toml


@lru_cache(1)
# @typechecked
def get_db_engine(config_file: str = "config.toml") -> Engine:
    config = toml.load(config_file)
    # 创建 ClickHouse SQLAlchemy 引擎
    engine = create_engine(
        f"clickhouse://{config['clickhouse']['user']}:{config['clickhouse']['pw']}@localhost:8123/coins"
    )
    return engine


def add_to_factor(expname: str, start: str, end: str, timeframe: str):
    start = datetime.strptime(start, "%Y%m%d")
    end = datetime.strptime(end, "%Y%m%d") + timedelta(days=1)

    table = f"experiment_{timeframe}"
    timeframe = timeframe.replace("m", "T")
    indices = pd.date_range(start=start, end=end, freq=timeframe)[:-1]
    df = pd.DataFrame(index=indices, columns=["expname", "money"])
    df["expname"] = expname
    df["money"] = np.random.random(len(df)) + 1
    df["time"] = indices
    df.to_sql(table, get_db_engine(), index=False, if_exists="append")


if __name__ == "__main__":
    add_to_factor("exprand1", "20200101", "20250208", "1m")
